package com.uduemc.biso.node.core.common.entities.publishdata.databody.containerdata;

import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;

import com.uduemc.biso.node.core.entities.SContainer;

import lombok.Data;
import lombok.ToString;
import lombok.experimental.Accessors;
import lombok.extern.slf4j.Slf4j;

/**
 * 容器写入数据库数据结构
 * 
 * @author guanyi
 *
 */
@Data
@ToString
@Accessors(chain = true)
@Slf4j
public class ContainerDataItemInsert {

	private String tmpId;
	private String tmpParentId;
	private String tmpBoxId;

	private long typeId;
	private long parentId;
	private long boxId;

	private long siteId;
	private long pageId;
	private short area;

	private String name;
	private int orderNum;
	private String config;

	// 引用的资源
	private List<RepertoryId> repertory;

	// 递归情况下的子集
	private List<ContainerDataItemInsert> children;

	public SContainer getSContainer(long hostId, long siteId, Map<String, Long> tempIdWithId) {
		long pageId = this.getPageId();
		Long dParentId = null;
		if (this.getParentId() > -1) {
			dParentId = this.getParentId();
		} else {
			Iterator<Entry<String, Long>> iterator = tempIdWithId.entrySet().iterator();
			while (iterator.hasNext()) {
				Entry<String, Long> next = iterator.next();
				String key = next.getKey();
				Long value = next.getValue();
				if (this.getTmpParentId().equals(key)) {
					dParentId = value;
					break;
				}
			}
		}
		if (dParentId == null || dParentId.longValue() < 0L) {
			log.error("未能找到临时 tmpParentId 对应的数据库中的 id! this.getParentId():" + this.getTmpParentId() + " tempIdWithId:"
					+ tempIdWithId.toString());
			return null;
		}

		Long dBoxId = null;
		if (this.getBoxId() > -1) {
			dBoxId = this.getBoxId();
		} else {
			Iterator<Entry<String, Long>> iterator = tempIdWithId.entrySet().iterator();
			while (iterator.hasNext()) {
				Entry<String, Long> next = iterator.next();
				String key = next.getKey();
				Long value = next.getValue();
				if (this.getTmpBoxId().equals(key)) {
					dBoxId = value;
					break;
				}
			}
		}
		if (dBoxId == null || dBoxId.longValue() < 0L) {
			log.error("未能找到临时 tmpBoxId 对应的数据库中的 id! this.getBoxId():" + this.getTmpBoxId() + " tempIdWithId:"
					+ tempIdWithId.toString());
			return null;
		}

		SContainer sContainer = new SContainer();
		sContainer.setHostId(hostId);
		sContainer.setSiteId(siteId);
		sContainer.setPageId(pageId);
		sContainer.setParentId(dParentId);
		sContainer.setArea(this.getArea());
		sContainer.setTypeId(this.getTypeId());
		sContainer.setBoxId(dBoxId);
		sContainer.setStatus((short) 0);
		sContainer.setName(this.getName());
		sContainer.setOrderNum(this.getOrderNum());
		sContainer.setConfig(this.getConfig());
		return sContainer;
	}
}
